#!/usr/bin/env python
# _*_coding:utf-8_*_

"""
@author:gao
@file: testDemo.py
@time: 2018/09/{DAY}
"""
from PyQt5.QtCore import QObject, pyqtSignal, QRunnable, QMutex, QWaitCondition, QMutexLocker
import pathlib
import time
from gui import constant
from utils.log_util import loggings


class Signal(QObject):
    completeSignal = pyqtSignal(object)
    errorSignal = pyqtSignal(object, object)
    progressSignal = pyqtSignal(object, object)
    test_end = pyqtSignal()
    move_signal = pyqtSignal(object)
    test_result = pyqtSignal(object)


class MeasureThread(QRunnable):
    def __init__(self, test_seq):
        super().__init__()
        self.signal = Signal()
        self.test_seq = test_seq
        self.file_path = constant.PLANS_FILE
        self.path = [str(i) for i in list(pathlib.Path(self.file_path).rglob("*.py"))]
        self.is_wafer = True
        self.flag = True
        self.ml = None
        self.test_mutex = QMutex()
        self.test_cond = QWaitCondition()
        self._isPause = True

    def run(self):
        if self.ml is None:
            self.ml = QMutexLocker(self.test_mutex)
        cache_subdie_name = self.test_seq[0].subdie
        try:
            # 使用探针台
            if self.is_wafer:
                while self.flag:
                    for test_item in self.test_seq:
                        # if self._isPause:
                            # self.test_cond.wait(self.ml.mutex())
                        self.pause()
                        if self.flag:
                            if test_item.subdie == cache_subdie_name:
                                try:
                                    self.exec_test(test_item)
                                except Exception as e:
                                    if "access violation reading" not in str(e):
                                        loggings.error(f"MeasureThread,wafer{e}")
                                        self.signal.errorSignal.emit("pyvisa_error", f"{e}")
                                        break
                                    else:
                                        loggings.error(f"MeasureThread_access violation reading_,{e}")
                                        continue
                            else:
                                cache_subdie_name = test_item.subdie
                                self.signal.move_signal.emit(1)
                                self.pause()
                                self.exec_test(test_item)
                        else:
                            print("self.flag",self.flag)
                            return
                    else:
                        cache_subdie_name = self.test_seq[0].subdie
                        self.signal.move_signal.emit(1)
                        self.pause()
                print("test_end")
                self.signal.test_end.emit()
            else:
                while self.flag:
                    for test_item in self.test_seq:
                        if test_item.subdie == cache_subdie_name:
                            test_path = pathlib.Path(self.file_path) / f"{test_item.test_pro}.py"
                            if str(test_path) in self.path:
                                try:
                                    new_file_path = test_path
                                    with open(new_file_path, 'r', encoding="utf-8") as f:
                                        exec(f.read(), {"para": test_item.test_set})
                                except Exception as e:
                                    loggings.error(f"MeasureThread,in{e}")
                                    self.signal.errorSignal.emit("pyvisa_error", str(e))
                                    break
                            # self.signal.last_signal.emit(1)
                            self.signal.test_result.emit(1)
                        else:
                            self.pause()
                            self.signal.test_result.emit(2)
                            cache_subdie_name = test_item.subdie
                    else:
                        self.signal.completeSignal.emit(1)
                        break
            self.ml.unlock()
            print("unlock")
        except Exception as e:
            loggings.error(f"MeasureThread,{e}")

    def exec_test(self, test_item):
        test_path = pathlib.Path(self.file_path) / f"{test_item.test_pro}.py"
        if str(test_path) in self.path:
            new_file_path = test_path
            with open(new_file_path, 'r', encoding="utf-8") as f:
                exec(f.read(), {"para": test_item.test_set})

    def pause(self):
        self._isPause = True
        if self._isPause:
            self.test_cond.wait(self.ml.mutex())

    def resume(self):
        self._isPause = False
        time.sleep(0.5)
        self.test_cond.wakeAll()


    def pause_thread(self):
        self._isPause = True

    def cancel_thread(self):
        self.resume()
        self.flag = False
        self._isPause = False
